import { View, Ad } from '@tarojs/components';
import Icon from 'components/Icon'
import Taro, { useRouter } from '@tarojs/taro';
import dayjs from 'dayjs'
import { useEffect, useRef, useState } from 'react';
import s from './index.module.scss'
import {ads} from 'components/CodeCard'
import getSystemInfo from 'utils/getSystemInfo';
const {platform} = getSystemInfo()

const isPC = ['mac', 'windows'].includes(platform)
let _navigate = isPC ? Taro.navigateTo : Taro.redirectTo

export default function Index() {
  const {params} = useRouter();
  const ad = useRef<any>(null)
  const [count, setCount] = useState(0)
  
  const {title = '', url = ''} = params

  let date = dayjs().format('YYYYMMDD')
  let __path = `/pages/webview/index?url=${url}&title=${title}`;

  useEffect(() => {
    const cache = Taro.getStorageSync(`adcount:${date}`) || 0
    let __count = parseInt(cache);
    setCount(__count);
    console.log('广告阅读次数: ', __count)

    if (__count >= 6) {
      _navigate({url: __path})
      return
    }

    setTimeout(() => {
      ad.current = Taro.createRewardedVideoAd({
        adUnitId: ads.ad15
      })
  
      ad.current.onLoad(() => {
        // ad.current.show()
      })
      ad.current.onError((err) => {
        console.log(err)
      })
      ad.current.onClose((res) => {
        if (res.isEnded) {
          __count += 1
          Taro.setStorageSync(`adcount:${date}`, `${__count}`)
          _navigate({url: __path})
        }
        if (!res.isEnded) {
          // Taro.navigateBack()
        }
      })
    }, 100)
  }, [])

  return (
    <View id={s.wrapper}>
      <View id={s.ad_wrapper}>
        <Ad unitId="adunit-52af3e01a0726ccf" />
      </View>

      <div id={s.divider}></div>

      <div id={s.tip}>
        <span id={s.atitle}>{decodeURIComponent(title)}</span>
        一文是由作者<strong id={s.author}>这波能反杀</strong>精心创作的高质量内容，为了鼓励作者再接再厉，持续创作，观看一则激励广告解锁文章吧 ^_^
      </div>

      <div id={s.divider}></div>

      <div id={s.rule_title}>码易观看广告规则：</div>
      <div id={s.rule}>每人每日完整观看六条激励广告，可在当日解锁全站免费文章内容。广告次数会在次日重置。</div>

      <div id={s.divider}></div>

      <div id={s.rule_title}>今日已观看广告数量</div>
      <div id={s.ads}>
        {['1', '2', '3', '4', '5', '6'].map((item, index) => (
          <div 
            key={item} 
            id={s.ad_light} 
            className={index < count ? s.active : ''}
          ></div>
        ))}
      </div>

      <div id={s.divider}></div>

      <div 
        id={s.btn} 
        onClick={() => ad.current.show()}
      >
        <Icon style={{marginRight: '6px'}} name='rect_194' size={22} />
        点击观看广告并解锁文章
      </div>
    </View>
  )
}